# @Time : 2023/1/10
# @Author : SDAJAVA

import requests
from bs4 import BeautifulSoup
import urllib.request

url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx'

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
}

response = requests.get(url=url, headers=headers)
content = response.text
# print(content)

soup = BeautifulSoup(content, 'lxml')

viewstate = soup.select('#__VIEWSTATE')[0].attrs.get('value')

viewstategenerator = soup.select('#__VIEWSTATEGENERATOR')[0].attrs.get('value')

print(viewstate)
print(viewstategenerator)
# 获取验证码图片
image_url = 'https://so.gushiwen.cn/RandCode.ashx'
code = soup.select('#imgCode')[0].attrs.get('src')
code_url = 'https://so.gushiwen.cn' + code

# urllib.request.urlretrieve(url=code_url, filename='code.jpg')

session = requests.session()
response_code = session.get(code_url)
content_code = response_code.content
# wb模式就是将二进制数据写入文件
with open('code.jpg', 'wb') as fp:
    fp.write(content_code)

code_name = input("请输入验证码：")
post_url = 'https://so.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fso.gushiwen.cn%2fuser%2fcollect.aspx'
post_data = {
    '__VIEWSTATE': viewstate,
    '__VIEWSTATEGENERATOR': viewstategenerator,
    'from': 'http://so.gushiwen.cn/user/collect.aspx',
    'email': '491484974@qq.com',
    'pwd': '526542033',
    'code': code_name,
    'denglu': '登录'
}

post_response = session.post(url=post_url, headers=headers, data=post_data)

post_content = post_response.text

with open('gushiwen.html', 'w', encoding="utf-8") as fp:
    fp.write(post_content)
